package com.freesun.shop.service.imp;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.freesun.shop.entity.Sku;
import com.freesun.shop.mapper.SkuMapper;

import com.freesun.shop.service.SkuService;
import org.apache.dubbo.config.annotation.Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Map;

/**
 * <p>
 * 单品SKU表 服务实现类
 * </p>
 *
 * @author zf
 * @since 2019-11-13
 */
@Service
public class SkuServiceImpl extends ServiceImpl<SkuMapper, Sku> implements SkuService {

    private static Logger logger = LoggerFactory.getLogger(SkuServiceImpl.class);
    /**
     * 扣减库存
     * @param skuCount
     */
    @Autowired
    private SkuMapper skuMapper;
    @Override
    public void decrStok(Map<Long, Integer> skuCount) {
        if (skuCount == null || skuCount.isEmpty()) {
            throw new RuntimeException("库存数据错误");
        }
        logger.info("执行删减库存:{}",skuCount);
        skuCount.forEach((skuId,num) ->{
            Sku sku = skuMapper.selectById(skuId);
           Integer subNum= sku.getStocks()-num;
            if (subNum < 0) {
                throw new RuntimeException("商品:"+skuId+"库存不足");
            }
            sku.setStocks(subNum);
            skuMapper.updateById(sku);
        });
    }
}
